import matplotlib.pyplot as plt
import os
from matplotlib.font_manager import FontProperties


class DrawImg:
    def __init__(self):
        self.my_BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
        # 用于matplotlib解析中文字体
        self.font_path = os.path.join(self.my_BASE_DIR, 'static', 'txt_collect', 'STXINGKA.TTF')

    def draw(self, xAxis, yAxis, name):
        plt.rcParams['font.sans-serif'] = ['SimHei']  # 指定默认字体
        plt.rcParams['axes.unicode_minus'] = False  # 解决保存图像是负号'-'显示为方块的问题
        font = FontProperties(fname=self.font_path)  # 指定字体文件路径

        # 数据
        # categories = ['Category1', 'Category2', 'Category3', 'Category4', 'Category5']   -------x轴标题
        # values = [10, 15, 7, 10, 5]  ----------y轴数值

        # 创建柱状图
        # plt.bar(categories, values)
        plt.bar(xAxis, yAxis)

        # 添加标题和标签
        # plt.title('My Bar Chart')
        plt.title(name)
        # 设置x轴标签并旋转45度
        plt.xticks(rotation=45)
        plt.xlabel('Categories')
        plt.ylabel('Values')

        # 显示图形
        # plt.show()

        # 绘图路径
        draw_path = os.path.join(self.my_BASE_DIR, 'static', 'picture', name + ".png")
        # 将图像保存到本地
        plt.savefig(draw_path)


# 以脚本方式启动
if __name__ == "__main__":
    # 捕捉异常错误
    try:
        di = DrawImg()
        categories = ['Category1', 'Category2', 'Category3', 'Category4', 'Category5']
        values = [10, 15, 7, 10, 5]
        di.draw(categories, values, 'test')
    except Exception as e:
        print("错误:", e)
